import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';

import 'package:ft_reader/beans/book_info_bean.dart';
import 'package:ft_reader/blocs/book_info_bloc.dart';
import 'package:ft_reader/common/utils/constans.dart';
import 'package:ft_reader/pages/details/comment.dart';
import 'package:ft_reader/pages/details/read_page.dart';
import 'package:ft_reader/pages/details/same_category_books.dart';
import 'package:ft_reader/pages/details/catalog_page.dart';
import 'package:ft_reader/widgets/loading_widget.dart';

// 详情
class InfoPage extends StatefulWidget {
  final String bookName;

  final int bookId;

  const InfoPage({Key key, this.bookName, this.bookId}) : super(key: key);
  @override
  _InfoPage createState() => _InfoPage();

}

class _InfoPage extends State<InfoPage>
  with AutomaticKeepAliveClientMixin{
  BookInfoBean _bookInfoBean;

  bool _isExpanded = false;

  BookInfoBloc _bookInfoBloc = new BookInfoBloc();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _bookInfoBloc.fetchBookInfo(widget.bookId);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: StreamBuilder(
        builder: (BuildContext context, AsyncSnapshot<BookInfoBean> content) {
          if (content.hasData) {
            _bookInfoBean = content.data;
            return _buildNestedScrollView(_bookInfoBean);
          } else {
            return Center(
              child: LoadingWidget(
                color: Theme.of(context).primaryColor,
              ),
            );
          }
        },
        stream: _bookInfoBloc.bookInfoData,
      ),
    );
  }

  NestedScrollView _buildNestedScrollView(BookInfoBean book) {
    return NestedScrollView(
      headerSliverBuilder: _sliverBuilder,
      body: _body(),
    );
  }

  List<Widget> _sliverBuilder(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        expandedHeight: 220,
        floating: false,
        pinned: true,
        title: Text(
          "${_bookInfoBean.data.name}详情"
        ),
        flexibleSpace: FlexibleSpaceBar(
          collapseMode: CollapseMode.parallax,
          background: Stack(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: CachedNetworkImageProvider(
                      _bookInfoBean.data.img
                    ),
                    fit: BoxFit.cover
                  )
                ),
                // 高斯模糊
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 12.0, sigmaY: 12.0),
                  child: Container(
                    color: Colors.black.withOpacity(0.4),
                  ),
                ),
              ),
              Positioned(
                child: _info(),
                left: 40,
                top: 120,
              )
            ],
          ),
        ),
      )
    ];
  }

  Widget _body() {
    return Stack(
      children: <Widget>[
        SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              _desc(),
              _catalog(),
              _author(),
              _category(),
              _comment(),
            ],
          ),
        ),
        Positioned(
          bottom: 0,
          child: Container(
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
            height: 50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                StreamBuilder(
                  builder: (BuildContext context, AsyncSnapshot<bool> isAdd) {
                   if (isAdd.hasData) {
                     return GestureDetector(
                      child: Container(
                        height: 50,
                        width: 100,
                        padding: EdgeInsets.only(left: 20.0),
                        child: Row(
                          children: <Widget>[
                            isAdd.data
                              ? Icon(
                                  Icons.check,
                                  color: Theme.of(context).primaryColor.withOpacity(0.8),
                                )
                              : Icon(
                                Icons.add,
                                color: Theme.of(context).primaryColor.withOpacity(0.8),
                            ),
                            isAdd.data
                                ? Text(
                                    '已添加',
                                    style: TextStyle(
                                        color: Theme.of(context)
                                            .primaryColor
                                            .withOpacity(0.8)
                                    ),
                            )
                                : Text(
                                  '加入书架',
                                  style: TextStyle(
                                      color: Theme.of(context)
                                          .primaryColor
                                          .withOpacity(0.8)
                                  ),
                            )
                          ],
                        ),
                      ),
                       onTap: isAdd.data
                          ? () {
                              print("删除");
                            }
                          : () {
                              print("添加");
                            },
                     );
                   } else {
                     return Container();
                   }
                  },
                  stream: _bookInfoBloc.addStoreSate,
                ),
                GestureDetector(
                  child: Container(
                    height: 50,
                    width: 100,
                    color: Theme.of(context).primaryColor.withOpacity(0.8),
                    child: Center(
                      child: Text(
                        '立即阅读',
                        style: TextStyle(
                          color: Colors.white
                        ),
                      ),
                    ),
                  ),
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(builder: (BuildContext context) {
                        return ReadPage(widget.bookId);
                      })
                    );
                  },
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  // 文本信息
  Widget _infoText (String content) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: Text(
        content,
        style: TextStyle(
          fontSize: 14.0,
          color: Colors.white,
          fontWeight: FontWeight.w500
        ),
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
      ),
    );
  }

  Widget _info() {
    return Container(
      child: Row(
        children: <Widget>[
          Hero(
            tag: widget.bookId,
            child: CachedNetworkImage(
              imageUrl: _bookInfoBean.data.img,
              width: 90,
                height: 120,
              fit: BoxFit.cover,
            ),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(left: 10),
                child: Text(
                  _bookInfoBean.data.name,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                    fontSize: 16.0,
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(bottom: 10, top: 10),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    _infoText(_bookInfoBean.data.author),
                    Icon(
                      Icons.fiber_manual_record,
                      size: 6,
                      color: Colors.white,
                    ),
                    _infoText(_bookInfoBean.data.cName),
                    Icon(
                      Icons.fiber_manual_record,
                      size: 6,
                      color: Colors.white,
                    ),
                    _infoText(_bookInfoBean.data.bookStatus),
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  // 描述
  Widget _desc() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          margin: EdgeInsets.all(20),
          child: Text(
            '作品简介',
            style: TextStyle(
              color: Theme.of(context).primaryColor,
              fontSize: 16,
              fontWeight: FontWeight.w400
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(bottom: 10),
          child: GestureDetector(
            onTap: () {
              setState(() {
                _isExpanded = !_isExpanded;
              });
            },
            child: Card(
              elevation: 0,
              child: Container(
                margin: EdgeInsets.all(20),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        _bookInfoBean.data.desc,
                        style: TextStyle(
                          fontWeight: FontWeight.w100,
                          color: Colors.black54,
                          fontSize: 18.0
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: _isExpanded ? 1000 : 3,
                      ),
                    ),
                    _isExpanded
                      ? Container()
                      : Align (
                          alignment: Alignment.bottomRight,
                          child: Icon(
                            Icons.expand_more,
                            color: Theme.of(context).primaryColor.withOpacity(0.8),
                          ),
                    )
                  ],
                ),
              ),
            ),
          ),
        )
      ],
    );
  }

  // 目录
  Widget _catalog() {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: GestureDetector(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (BuildContext context) {
              return CatalogPage(_bookInfoBean.data.id);
            })
          );
        },
        child: Card(
          elevation: 0,
          child: Container(
            margin: EdgeInsets.all(20.0),
            child: Row(
              children: <Widget>[
                Text(
                  '目录',
                  style: TextStyle(
                    fontSize: 20.0
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Text(
                        _bookInfoBean.data.lastChapter,
                        style: TextStyle(
                          fontSize: 14
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      Text(
                        _bookInfoBean.data.lastTime,
                        style: TextStyle(
                          fontSize: 14.0,
                        ),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 作者
  Widget _author() {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: GestureDetector(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (BuildContext context) {
              return SameCategoryBooksPage(_bookInfoBean.data.sameCategoryBooks);
            })
          );
        },
        child: Card(
          elevation: 0,
          child: Container(
            margin: EdgeInsets.all(20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '作者 - ${_bookInfoBean.data.author}',
                  style: TextStyle(
                    fontSize: 16.0
                  ),
                ),
                Text(
                  "共有${_bookInfoBean.data.sameCategoryBooks.length.toString()}本作者相关书籍"
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 分类
  Widget _category() {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: GestureDetector(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (BuildContext context) {
              return SameCategoryBooksPage(_bookInfoBean.data.sameCategoryBooks);
            })
          );
        },
        child: Card(
          elevation: 0,
          child: Container(
            margin: EdgeInsets.all(20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  '类型 - ${_bookInfoBean.data.cName}',
                  style: TextStyle(
                    fontSize: 16.0
                  ),
                ),
                Text(
                    "共有${_bookInfoBean.data.sameCategoryBooks.length.toString()}本同类型推荐书籍"
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 评论
  Widget _comment() {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      child: GestureDetector(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (BuildContext context) {
              return CommentPage(bookInfo: _bookInfoBean,);
            })
          );
        },
        child: Card(
          elevation: 0,
          child: Container(
            margin: EdgeInsets.all(20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  "查看评论",
                  style: TextStyle(
                    fontSize: 16.0,
                  ),
                ),
                IconButton(
                  icon: Icon(MyIcon.nextIcon),
                  onPressed: () {
                    print("查看评论");
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _bookInfoBloc?.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

}
